import re

from flask import Blueprint, jsonify

from libs.db import DB
from libs.scheduler_v2 import TaskStatus

task_bp = Blueprint('task', __name__)


@task_bp.route('/task/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    sql = """
    DELETE FROM task where id = ?
    """
    DB().run_sql(sql, (task_id,))
    return jsonify({"code": 0})


@task_bp.route('/task/<int:task_id>/run_next', methods=['POST'])
def run_next(task_id):
    sql = """
    UPDATE task set priority = 9, execute_time = DATETIME() where id = ?
    """
    DB().run_sql(sql, (task_id,))
    return jsonify({"code": 0})


@task_bp.route('/tasks', methods=['GET'])
def list_tasks():
    sql = """
        SELECT id, user_id, task_id, command, priority, create_time, execute_time, start_time, end_time, status,
        CASE
            WHEN execute_time > DATETIME() THEN priority / 10
            ELSE priority
        END as sort_priority
        FROM task
        WHERE status in ('pending', 'running') or start_time >= DATETIME('now', '-24 hours')
        ORDER BY sort_priority DESC, execute_time asc
    """
    rows = DB().fetch_all(sql)
    result = []
    running_users = []
    task_names = []
    for row in rows:
        cmd = row[3]
        retry = 0
        match = re.search(r'--retry=(\d+)', cmd)
        if match:
            retry = match.group(1)
        match = re.search(r'python\s+(\S+)\.py', cmd)
        task_name = 'unknown'
        if match:
            task_name = match.group(1)
        if task_name not in task_names:
            task_names.append(task_name)
        status = row[9]
        if status == TaskStatus.RUNNING:
            user_id = row[1]
            if user_id not in running_users:
                running_users.append(user_id)
        result.append({
            "id": row[0],
            "user_id": row[1],
            "task_id": row[2],
            "command": row[3],
            "priority": row[4],
            "create_time": row[5],
            "execute_time": row[6],
            "execute_date": str(row[6])[:10],
            "start_time": row[7],
            "end_time": row[8],
            "status": row[9],
            "retry": retry,
            "task_name": task_name
        })
    return jsonify({"code": 0, "list": result, "running_users": running_users, "task_names": task_names})


@task_bp.route('/user_task_summaries')
def task_summary():
    task_summary_sql = """
    SELECT user_id, status, count(*) as task_count
    FROM task
    WHERE start_time >= DATETIME('now', '-24 hours')
    GROUP BY user_id, status
    """
    rows = DB().fetch_all(task_summary_sql)
    result = {}
    for row in rows:
        user_id = row[0]
        status = row[1]
        task_count = row[2]
        if user_id not in result:
            result[user_id] = {}
        result[user_id][status] = task_count
    return jsonify({"code": 0, "result": result})
